﻿#include "TreeWidget_DisplayScriptList.h"

#include <qlist.h>
#include <qmessagebox.h>

#include "ScriptInstruction.h"
#include "InstructionLoop.h"

TreeWidget_DisplayScriptList::TreeWidget_DisplayScriptList(QWidget *parent)
  : QTreeWidget(parent)
{
}

TreeWidget_DisplayScriptList::~TreeWidget_DisplayScriptList()
{
  for (int i = 0; i < topLevelItemCount(); ++i)
    {
      circularDelete(takeTopLevelItem(i));
    }
}
void TreeWidget_DisplayScriptList::circularDelete(QTreeWidgetItem* parent)
{
  for (int i = 0; i < parent->childCount(); ++i)
    {
      circularDelete(parent->child(i));
    }
  delete parent;
}

void TreeWidget_DisplayScriptList::slot_showCurrentInstruction(int instructionIndex)
{
  QBrush brush;
  brush.setStyle(Qt::SolidPattern);
  if (lastHighLightNode != Q_NULLPTR)
    {
      brush.setColor(Qt::white);
      lastHighLightNode->setBackground(0, brush);
    }
  brush.setColor(Qt::green);
  QTreeWidgetItem* currentItem = itemList.value(instructionIndex);
  currentItem->setBackground(0, brush);
  setCurrentItem(currentItem);
  lastHighLightNode = currentItem;
}

void TreeWidget_DisplayScriptList::slot_clearCurrentInstruction()
{
  QBrush brush;
  brush.setStyle(Qt::SolidPattern);
  if (lastHighLightNode != Q_NULLPTR) {
      brush.setColor(Qt::white);
      lastHighLightNode->setBackground(0, brush);
    }
  setCurrentItem(Q_NULLPTR);
}

void TreeWidget_DisplayScriptList::slot_updateScriptList(QList<ScriptInstruction*> scriptList)
{
  clear();
  itemList.clear();//清空记录代码块的列表
  lastHighLightNode = Q_NULLPTR;
  if (scriptList.isEmpty()) {//整个代码块都是空的就不用继续解析了
      return;
    }
  QList<QTreeWidgetItem*> loopNodeStack;//循环节点栈
  QList<uint> instructionCountStack;//指令计数栈
  for(ScriptInstruction* scriptInstruction:scriptList)
    {
      QTreeWidgetItem* newNode=new QTreeWidgetItem();//创建新的节点
      newNode->setText(0,scriptInstruction->toString());//给节点命名
      itemList.append(newNode);
      if(loopNodeStack.isEmpty())//若循环节点栈为空则说明当前处于顶层
        {
          addTopLevelItem(newNode);//将新节点添加到顶层的最后
        }
      else//若循环节点栈不为空则说明当前处于某个循环节点下
        {
          loopNodeStack.last()->addChild(newNode);//将新节点添加到栈顶所指的循环节点下
          if(!--instructionCountStack.last())
            {
              //如果指令计数栈栈顶值自减一后等于零，则说明该层循环结束
              loopNodeStack.removeLast();//循环节点栈出栈
              instructionCountStack.removeLast();//指令计数栈出栈
            }
        }
      if(ScriptInstruction::MetaInstruction_Loop==scriptInstruction->getInstructionFlag())
        {
          //如果当前脚本指令是循环指令
          //添加该循环指令的指令计数到指令计数栈
          instructionCountStack.append(dynamic_cast<InstructionLoop*>(scriptInstruction)->getInstructionCount());
          loopNodeStack.append(newNode);//添加该节点到循环节点栈，表明当前处于的层级在该循环下
        }
    }
}

